package org.lq.us.web.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lq.us.util.ConfigHelper;

import lombok.extern.log4j.Log4j;

/**
 * Servlet Filter implementation class LoginFilter
 */
//@WebFilter(urlPatterns = {"/*","/page/*","/html/*"})
@Log4j
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String allow = ConfigHelper.getProjectAllow();
		log.info("允许访问的列表 : "+allow);
		 List<String> allowList= Arrays.asList(allow.split(","));
		 // http :// 服务器地址(localhost)  : 端口号 / 项目名称
		 String baseURL = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+"/";
		 System.out.println(baseURL);
		 String path = req.getServletPath();
		 log.info("请求地址 : "+path);
		 String ext = path.substring(path.lastIndexOf(".")+1);
		 String requestPath = path.substring(path.lastIndexOf("/")+1);
		 Object obj = req.getSession().getAttribute("user");
		 if(allowList.contains(ext) || allowList.contains(requestPath) || obj!=null) {
			 chain.doFilter(request, response);
		 }else {
			 resp.sendRedirect(baseURL+"login.html");
		 }
		 
		 
		 
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
